package com.example.userdepartment.service.impl;

import com.example.userdepartment.entity.Department;
import com.example.userdepartment.entity.User;
import com.example.userdepartment.mapper.DepartmentMapper;
import com.example.userdepartment.mapper.UserMapper;
import com.example.userdepartment.service.UserService;
import com.example.userdepartment.util.ExcelUtil;
import com.example.userdepartment.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public List<User> findAll() {
        return userMapper.selectAll();
    }

    @Override
    public User findById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public User findWithDeptById(Integer id) {
        return userMapper.selectWithDeptById(id);
    }

    @Override
    @Transactional
    public User add(User user) {
        userMapper.insert(user);
        return user;
    }

    @Override
    @Transactional
    public User update(User user) {
        userMapper.update(user);
        return userMapper.selectById(user.getId());
    }

    @Override
    @Transactional
    public boolean delete(Integer id) {
        return userMapper.delete(id) > 0;
    }

    @Override
    @Transactional
    public boolean batchDelete(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        return userMapper.batchDelete(ids) > 0;
    }

    @Override
    public List<User> findByDepartmentId(Integer departmentId) {
        return userMapper.selectByDepartmentId(departmentId);
    }

    @Override
    public List<User> searchUsers(String keyword, Integer departmentId) {
        logger.info("搜索用户 - 关键字: {}, 部门ID: {}", keyword, departmentId);
        
        // 如果关键字和部门ID都为空，则返回所有用户
        if ((keyword == null || keyword.trim().isEmpty()) && departmentId == null) {
            return findAll();
        }
        
        List<User> result = new ArrayList<>();
        
        // 根据部门ID筛选
        if (departmentId != null) {
            List<User> usersByDept = userMapper.selectByDepartmentId(departmentId);
            
            // 如果关键字也不为空，进一步筛选
            if (keyword != null && !keyword.trim().isEmpty()) {
                String lowerKeyword = keyword.toLowerCase().trim();
                return usersByDept.stream()
                        .filter(user -> 
                            (user.getUsername() != null && user.getUsername().toLowerCase().contains(lowerKeyword)) ||
                            (user.getRealName() != null && user.getRealName().toLowerCase().contains(lowerKeyword)) ||
                            (user.getEmail() != null && user.getEmail().toLowerCase().contains(lowerKeyword)) ||
                            (user.getPhone() != null && user.getPhone().contains(lowerKeyword))
                        )
                        .collect(Collectors.toList());
            } else {
                return usersByDept;
            }
        } else {
            // 只根据关键字搜索
            String lowerKeyword = keyword.toLowerCase().trim();
            List<User> allUsers = findAll();
            return allUsers.stream()
                    .filter(user -> 
                        (user.getUsername() != null && user.getUsername().toLowerCase().contains(lowerKeyword)) ||
                        (user.getRealName() != null && user.getRealName().toLowerCase().contains(lowerKeyword)) ||
                        (user.getEmail() != null && user.getEmail().toLowerCase().contains(lowerKeyword)) ||
                        (user.getPhone() != null && user.getPhone().contains(lowerKeyword))
                    )
                    .collect(Collectors.toList());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result importUsers(MultipartFile file) {
        try {
            List<User> users = ExcelUtil.parseUserExcel(file.getInputStream());
            if (users.isEmpty()) {
                return Result.error("导入数据为空");
            }

            // 验证并处理数据
            List<User> validUsers = new ArrayList<>();
            List<String> errorMessages = new ArrayList<>();
            int successCount = 0;
            int failCount = 0;

            for (int i = 0; i < users.size(); i++) {
                User user = users.get(i);
                try {
                    // 验证必填字段
                    if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getEmail())) {
                        errorMessages.add("第" + (i + 3) + "行: 用户名或邮箱为空");
                        failCount++;
                        continue;
                    }

                    // 检查用户名是否已存在
                    if (userMapper.selectByUsername(user.getUsername()) != null) {
                        errorMessages.add("第" + (i + 3) + "行: 用户名 " + user.getUsername() + " 已存在");
                        failCount++;
                        continue;
                    }

                    // 检查邮箱是否已存在
                    if (userMapper.selectByEmail(user.getEmail()) != null) {
                        errorMessages.add("第" + (i + 3) + "行: 邮箱 " + user.getEmail() + " 已存在");
                        failCount++;
                        continue;
                    }

                    // 处理部门信息 - 如果提供了部门名称，尝试查找对应的部门ID
                    if (user.getDepartmentName() != null && !user.getDepartmentName().isEmpty()) {
                        Department department = departmentMapper.selectByName(user.getDepartmentName());
                        if (department != null) {
                            user.setDepartmentId(department.getId());
                        } else {
                            // 获取所有部门名称，提供给用户参考
                            List<Department> allDepts = departmentMapper.selectAll();
                            String availableDepts = allDepts.stream()
                                    .map(Department::getName)
                                    .collect(Collectors.joining("、"));
                            
                            // 如果找不到对应的部门，设置为null并记录警告
                            user.setDepartmentId(null);
                            errorMessages.add("第" + (i + 3) + "行: 部门 '" + user.getDepartmentName() + "' 不存在，已设置为空。可用部门: " + availableDepts);
                        }
                    } else if (user.getDepartmentId() != null) {
                        // 如果提供了部门ID，验证是否存在
                        Department department = departmentMapper.selectById(user.getDepartmentId());
                        if (department == null) {
                            user.setDepartmentId(null);
                            errorMessages.add("第" + (i + 3) + "行: 部门ID " + user.getDepartmentId() + " 不存在，已设置为空");
                        }
                    }

                    user.setCreateTime(new Date());
                    user.setUpdateTime(new Date());

                    validUsers.add(user);
                    successCount++;
                } catch (Exception e) {
                    errorMessages.add("第" + (i + 3) + "行: 处理失败 - " + e.getMessage());
                    failCount++;
                }
            }

            // 批量插入有效用户
            if (!validUsers.isEmpty()) {
                userMapper.batchInsert(validUsers);
            }

            // 返回导入结果
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("successCount", successCount);
            resultMap.put("failCount", failCount);
            resultMap.put("errorMessages", errorMessages);

            return Result.success("成功导入" + successCount + "条记录，失败" + failCount + "条", resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入失败: " + e.getMessage());
        }
    }

    @Override
    public byte[] exportUsers() {
        try {
            List<User> users = userMapper.selectAll();
            // 查询每个用户的部门信息
            for (User user : users) {
                if (user.getId() != null) {
                    User userWithDept = userMapper.selectWithDeptById(user.getId());
                    if (userWithDept != null && userWithDept.getDepartment() != null) {
                        user.setDepartment(userWithDept.getDepartment());
                    }
                }
            }
            return ExcelUtil.exportUserData(users);
        } catch (IOException e) {
            logger.error("导出用户Excel出错", e);
            throw new RuntimeException("导出用户Excel出错: " + e.getMessage());
        }
    }
} 
 